import React from 'react'
import {Modal, ActionSheet} from 'antd-mobile'
import { NavLink } from 'react-router-dom'

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {actions} from '../../reducers'
import {actions as ProjectAction} from '../../reducers/project'

import utils from '../../common/utils'
import history from '../../history'
import moment from 'moment'

const {alert} = Modal

const get_user_url = (role, project) => {
    if (role == 'publish') {
        return `/profile/${project.project_user.user.id}`
    } else {
        return `/profile/${project.user.id}`
    }
}

const get_user_id = (role, project) => {
    if (role == 'publish') {
        return project.project_user.user.id
    } else {
        return project.user.id
    }
},
get_chat_url = (role, project) => `/contacts/detail/${get_user_id(role,project)}`

class Layout extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            type: null,
            id: 0,
        }
    }

    componentDidMount() {
        let type = utils.getQueryString('type'),
            id = utils.getQueryString('id'),
            project_id = utils.getQueryString('project_id')
        this.setState({type, id})
        this.props.get_project_detail(id, type)
    }

    the_nav_link(_path, label, key) {
       let type = utils.getQueryString('type'),
            id = utils.getQueryString('id'),
            project_id = this.props.project.project_id,
            url = `/project-detail/${_path}${_path=='introduction'?'/'+type:''}?type=${type}&id=${id}&project_id=${project_id}`

        return  <NavLink to={url} key={key}
                    replace activeClassName="active" 
                    isActive={()=>window.location.pathname.split("/")[2]==_path} 
                >{label}
                </NavLink>
    }

    delete_project = (project_id) => {
        alert('删除项目', '确认删除项目？', [
            { text: '取消', onPress: () => console.log('delete') },
            { text: '删除', onPress: () => this.props.delete_project(project_id) },
          ])
    }

    cancel_project = (project_id, role) => {
        alert('取消项目', '确认取消项目？', [
            { text: '取消', onPress: () => console.log('cancel') },
            { text: '确认', onPress: () => this.props.cancel_project(project_id, role) },
          ])
    }

    accept_project = (id) => {
        alert('接受项目', '确认接受项目？', [
            { text: '取消', onPress: () => console.log('cancel') },
            { text: '确认', onPress: () => this.props.accept_project(id) },
          ])
    }

    reject_project = id => {
        alert('拒绝项目', '确认拒绝项目？', [
            { text: '取消', onPress: () => console.log('cancel') },
            { text: '确认', onPress: () => this.props.reject_project(id) },
          ])
    }

    complete_project = (id, project_id) => {
        alert('完成项目', '确认完成项目？', [
            { text: '取消', onPress: () => console.log('cancel') },
            { text: '确认', onPress: () => this.props.complete_project(id, project_id) },
          ])
    }

    showActionSheet = (project_id, id) => {
        const BUTTONS = ['设置里程碑','添加项目进度','完成项目', '取消']
        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            // destructiveButtonIndex: BUTTONS.length - 2,
            // title: 'title',
            // message: 'I am description, description, description',
            maskClosable: true,
          },
          (buttonIndex) => {
            console.log(buttonIndex)
            switch (buttonIndex) {
                case 0:
                    history.push(`/milestone/${project_id}`)
                    break 
                case 1:
                    history.push(`/add-schedule?project_id=${project_id}`)
                    break
                case 2:
                    this.complete_project(id, project_id)
                    break
            }
          });
    }

    renderButton(project) {
        let _path = window.location.pathname.split("/")[2],
            type = utils.getQueryString('type'),
            project_id = this.props.project.project_id,
            id = this.props.project.id
        
        const rules = [
            {type: 'publish', status: 'draft', _path: 'introduction', btns: [
                {label: '编辑', callback: ()=>history.push(`/new-project/${project_id}`)},
            ]},
            {type: 'publish', status: 'working', _path: 'introduction', btns: [
                {label: '联系', callback: ()=>history.push(get_chat_url('publish', project)), admin: true},
                {label: '信息修订', callback: ()=>history.push(`/add-revision/${project_id}`)},
                
            ]},
            {type: 'publish', status: 'working', _path: 'schedule', btns: [
                {label: '联系', callback: ()=>history.push(get_chat_url('publish', project)) , admin: true},
                
            ]},
            {type: 'publish', status: 'publish', _path: 'introduction', btns: [
                {label: '分配项目', callback: ()=>history.push(`/assign?project_id=${project_id}`) , admin: true},
                {label: '信息修订', callback: ()=>history.push(`/add-revision/${project_id}`)},
                
            ]},
            {type: 'publish', status: 'done', _path: 'introduction', btns: [
                {label: '联系', callback: ()=>history.push(get_chat_url('publish', project)), admin: true },
            ]},
            {type: 'publish', status: 'publish', _path: 'comment', btns: [
                // {label: '提交', callback: ''},
            ]},
            {type: 'publish', status: 'cancel', _path: 'introduction', btns: [
                {label: '联系', callback: ()=>history.push(get_chat_url('publish', project)), admin: true },
                {label: '信息修订', callback: ()=>history.push(`/add-revision/${project_id}`)},
                
            ]},

            {type: 'grab', status: 'drop', _path: 'introduction', btns: [
                
            ]},
            {type: 'grab', status: 'pending', _path: 'introduction', btns: [
                {label: '接受项目', callback: ()=>this.accept_project(id)},
                {label: '拒绝项目', callback: ()=>this.reject_project(id)},
            ]},

            {type: 'execute', status: 'working', _path: 'introduction', btns: [
                {label: '联系需求方', callback: ()=>history.push(get_chat_url('execute', project)) },
                {label: '信息修订', callback: ()=>history.push(`/add-revision/${project_id}`)},
 
            ]},
            {type: 'execute', status: 'working', _path: 'schedule', btns: [
                {label: '更新项目进度', callback: ()=>this.showActionSheet(project_id, id)},
            ]},
            // {type: 'execute', status: 'done', _path: 'comment', btns: [
                
            // ]},
            {type: 'execute', status: true, _path: 'sub-project', manager: true, btns: [
                {label: '添加子项目', callback: ()=>history.push(`/new-project?parent_id=${project_id}`)},
            ]},
        ]

        let btns = []
        rules.map(x => {
            if (x.type==type&&
                (x.status==project.status||x.status==true)&&
                x._path==_path&&
                (x.manager==undefined || x.manager==this.props.userInfo.is_manager)
            ) {
                // 当前用户是管理员 && 不是项目的发布人 && 项目状态不是我抢单的 && 项目不是我执行的,只显示指定的按钮
                if (this.props.userInfo.is_admin && this.props.userInfo.id!=project.user_id 
                    && project.status!=='pending' && (project.project_user&&project.project_user.user_id!=this.props.userInfo.id)) {
                    btns = x.btns.filter(y => y.admin==true)
                } else {
                    btns = x.btns
                }
            }
        })
        
        if (btns[0]) {
            return <div className="btns">
                        { btns.map(x => {
                                return <a className="contact" key={x.id} onClick={()=>x.callback(project.id)}>{x.label}</a>
                            }
                        )}
                    </div>
        }
 
    }

    renderTabTitle(project) {
        let type = utils.getQueryString('type'),
            id = utils.getQueryString('id'),
            project_id = this.props.project.project_id,
            {project_user_id} = this.props.project

        const rules = [
            {type: 'publish', status: 'draft', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'button', label: '删除项目', callback: this.delete_project,
                    params: [project_id], admin: false},
            ]},
            {type: 'publish', status: 'publish', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'button', label: '删除项目', callback: this.delete_project,
                params: [project_id], admin: false},
            ]},
            {type: 'publish', status: 'pending', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'assigned', label: '我分配的'},
                {mode: 'button', label: '取消项目', callback: this.cancel_project,
                 params: [project_id, type], admin: false},
            ]},
            {type: 'publish', status: 'working', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'schedule', label: '项目进度'},
                {mode: 'button', label: '取消项目', callback: this.cancel_project,
                 params: [project_id, type], admin: false},
            ]},
            {type: 'publish', status: 'done', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'schedule', label: '项目历史'},
                {mode: 'nav', _path: 'comment', label: '项目评价'},
                {mode: 'nav', _path: 'point-income', label: '积分收益'},
            ]},
            {type: 'publish', status: 'cancel', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'schedule', label: '项目历史'},
                {mode: 'nav', _path: 'comment', label: '项目评价'},
                {mode: 'nav', _path: 'point-income', label: '积分收益'},
            ]},

            {type: 'grab', status: true, tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
            ]},

            {type: 'execute', status: 'publish', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                // {mode: 'button', label: '接受项目', callback: ''},
                // {mode: 'button', label: '拒绝项目', callback: ''},
            ]},
            {type: 'execute', status: 'working', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'sub-project', label: '子项目'},
                {mode: 'nav', _path: 'schedule', label: '项目进度'},
                {mode: 'button', label: '取消项目', callback: this.cancel_project,
                params: [project_user_id, type]},
            ]},
            {type: 'execute', status: 'done', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'schedule', label: '项目历史'},
                {mode: 'nav', _path: 'comment', label: '项目评价'},
                {mode: 'nav', _path: 'point-income', label: '积分收益'},
            ]},
            {type: 'execute', status: 'cancel', tabs: [
                {mode: 'nav', _path: 'introduction', label: '项目信息'},
                {mode: 'nav', _path: 'schedule', label: '项目历史'},
                {mode: 'nav', _path: 'comment', label: '项目评价'},
                {mode: 'nav', _path: 'point-income', label: '积分收益'},
            ]},

        ]
        let tabs = []
        rules.map(x => {
            let me_2_me = project.project_user&&project.project_user.user_id == project.user_id;
            if (x.type==type&& (x.status==project.status || x.status==true)) {
                if (this.props.userInfo.is_admin && (project.project_user&&this.props.userInfo.id!=project.project_user.user_id)) {
                    tabs = x.tabs.filter(y=>y.mode=='nav')
                } else {
                    tabs = x.tabs
                }
            }
            //自己发布自己执行不评价
            if (me_2_me) {
                tabs = tabs.filter(x=>x._path!=='comment')
            }
        })
        return <div class="title">
                    { tabs.map( (x, i) => {
                        if (x.mode=='nav') {
                            return this.the_nav_link(x._path, x.label, `tab-${i}`)
                        } else {
                            return <a key={`tab-${i}`} onClick={()=>x.callback(...x.params)}>{x.label}</a>
                        }
                    })}
                </div>
    }

    renderTimeOrWorker(project) {
        //投标中，显示剩余时间
        if (project.status=='pending') {
            let _last = utils.getLastTime(project.expect_at)
            return <div class="time">{_last.overtime?'超':'剩'}<i>{Math.abs(_last.d)}</i>天<i>{Math.abs(_last.h)}</i>小时</div>
        }
        //有执行人显示执行人
        let username = ''
        if (this.state.type=='execute') {
            return <span>执行者：{this.props.userInfo.nickname}</span>
        }
        if (project.project_user) {
            return <span>执行者：{project.project_user.user.nickname}</span>
        } 
        
        return null
    }

    render() {
        const { children, project } = this.props
        return(
            <React.Fragment>
                <div className="details margin">
                    <div className="head">
                        <div class="my-h3">
                            <div class="name">{project.title}</div>
                            {
                                project.status == 'working' ?
                                     <span>{project.format_remaining_time}</span>
                                    :<span>{moment(project.created_at).format('ll')}</span>
                            
                            }
                        </div>
                        <div className="p1">
                            <span>{utils.formatProjectStatus(project)}</span>
                            <em>{project.category_name}</em>
                        </div>
                        <div className="p2">
                            <span>发布者：{project.user.nickname}</span>
                            {this.renderTimeOrWorker(project)}
                        </div>

                        <div class="tabs">
                            {this.renderTabTitle(project)}
                        </div>
                    </div>
                    
                    <div className="content-box">
                    {React.cloneElement(this.props.children, 
                        {ref: 'switch' })
                    }
                    </div>
                </div>
                
                {this.renderButton(project)}
                
            </React.Fragment>
        )
    }
}

function mapStateToProps(state) {
    return {
      project: state.project.detail,
      userInfo: state.user.userInfo
    }
  }
  
  function mapDispatchToProps(dispatch) {
    return  {
      get_project_detail: bindActionCreators(ProjectAction.get_detail, dispatch),
      accept_project: bindActionCreators(ProjectAction.accept_project, dispatch),
      delete_project: bindActionCreators(ProjectAction.delete_project, dispatch),
      cancel_project: bindActionCreators(ProjectAction.cancel_project, dispatch),
      publish_project: bindActionCreators(ProjectAction.publish_project, dispatch),
      complete_project: bindActionCreators(ProjectAction.complete_project, dispatch),
      reject_project: bindActionCreators(ProjectAction.reject_project, dispatch)
    }
  }
  
  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(Layout)